package com.ming.learn.from.carl.doublepointer;

/*
题目：剑指Offer 05.替换空格
 */
public class Of20201228Offer05 {
    /*
    请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
    示例 1：
    输入：s = "We are happy."
    输出："We%20are%20happy."
     */
    public static void main(String[] args) {
        System.out.println(replaceSpace("I am CodeMing"));
    }

    private static String replaceSpace(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ')
                count++;
        }
        char[] chars = new char[s.length() + count * 2];
        for (int i = s.length() - 1, j = chars.length - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                chars[j--] = '0';
                chars[j--] = '2';
                chars[j--] = '%';
                continue;
            }
            chars[j--] = s.charAt(i);
        }
        return new String(chars);
    }
}
